package com.demo.cms.webapp.template.directive;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.views.freemarker.FreemarkerManager;
import org.springframework.beans.factory.annotation.Autowired;

import com.demo.common.ClassLoaderUtils;
import com.demo.common.StringUtils;
import com.demo.webapp.service.AccessStatisticsService;
import com.demo.webapp.service.AccessStatisticsService.TYPE;
import com.demo.webapp.views.freemarker.directive.core.BaseDirectiveSupport;

import freemarker.core.Environment;
import freemarker.core.Environment.TemplateDirectiveBodyEx;
import freemarker.ext.servlet.HttpRequestHashModel;
import freemarker.template.SimpleHash;
import freemarker.template.TemplateBooleanModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;

/**
 * 文章记录的自定义指令
 * 记录文章阅读&回复、顶&踩、收藏、其他的次数
 * @author ryuu.kk
 *
 */
public class RecordDirective extends BaseDirectiveSupport {

	/**
	 * 页面模板名
	 */
	private static final String RECORD_TEMPLATE_NAME = "classpath:/com/demo/cms/webapp/template/record.ftl";
	
	/**
	 * 动态加载的js模板
	 */
	private static final String RECORD_DYNAMIC_TEMPLATE = "classpath:/com/demo/cms/webapp/template/recordDynamicTemplate.ftl";
	/**
	 * 访问统计服务
	 */
	@Autowired
	private AccessStatisticsService accessStatisticsService;

	@SuppressWarnings("rawtypes")
	@Override
	public void preWriter(Environment env, TemplateDirectiveBodyEx bodyEx,
			TemplateModel[] loopVars, SimpleHash hash, Map params)
			throws IOException, TemplateException {
		// 统计对象ID
		Long id = null;
		// 统计对象名
		String name = "";
		// 统计对象类型
		String type = "read";
		// 是否动态
		boolean dynamic;
		// 重复计数标志,如果可以重复计数,那么可以执行多次顶，踩操作
		String repeat;
		
		// 获得ID
		id = getLong("id", params);
		if (id == null) {
			throw new TemplateException("自定义指令core_record的id不能为空", env);
		}
		// 获得是否动态调用
		dynamic = getBoolean("dynamic", params, Boolean.valueOf(getDefaultValue("dynamic")));
		// 获得重复标志
		repeat = getString("repeat", params, getDefaultValue("repeat"));
		
		hash.put("id", id);
		hash.put("name", name);
		hash.put("type", type);
		hash.put("dynamic", dynamic);
		hash.put("repeat", repeat);
		
		if (dynamic) {
			// 动态调用,不适用同步模式
			return;
		}
		// 阅读&回复
		int read = 0;		
		int replay = 0;
		// 顶&踩
		int up = 0;
		int down = 0;
		// 收藏
		int favour = 0;
		// 其他
		int other = 0;
		type = getString("type", params, getDefaultValue("type"));
		
		if (StringUtils.isNotEmpty(type)) {
			String[] ts = type.split(",");
			for (String t : ts) {
				String key = t.trim();
				if ("READ".equalsIgnoreCase(key)) {
					// 阅读
					read = accessStatisticsService.count(id, TYPE.READ);
				} else if ("REPLY".equalsIgnoreCase(key)) {
					// 回复
					replay = accessStatisticsService.count(id, TYPE.REPLY);
				} else if ("UP".equalsIgnoreCase(key)) {
					// 顶
					up = accessStatisticsService.count(id, TYPE.UP);
				} else if ("DOWN".equalsIgnoreCase(key)) {
					// 踩
					down = accessStatisticsService.count(id, TYPE.DOWN);
				} else if ("FAVOUR".equalsIgnoreCase(key)) {
					// 收藏
					favour = accessStatisticsService.count(id, TYPE.FAVOUR);
				} else if ("OTHER".equalsIgnoreCase(key)) {
					// 其他
					other = accessStatisticsService.count(id, TYPE.OTHER);
				}
			}
		}

		hash.put("read", read);
		hash.put("replay", replay);
		hash.put("up", up);
		hash.put("down", down);
		hash.put("favour", favour);
		hash.put("other", other);
		
		
		// 
	}

	@SuppressWarnings("rawtypes")
	@Override
	public String getTemplatePath(Map params) {
		String path = "";
		try {
			path = getString("path", params, RECORD_TEMPLATE_NAME);
		} catch (TemplateModelException e) {}
		return path;
	}
	
	@SuppressWarnings("rawtypes")
	protected String processSource(String source, SimpleHash hash, Map params)
			throws TemplateModelException, FileNotFoundException, MalformedURLException, URISyntaxException {
		source = super.processSource(source, hash, params);
		Object obj = hash.get("dynamic");
		if (obj instanceof TemplateBooleanModel) {
			Boolean dynamic = ((TemplateBooleanModel)obj).getAsBoolean();
			if (dynamic) {
				// 加载动态部分。
				String templatePath = RECORD_DYNAMIC_TEMPLATE;
				HttpRequestHashModel requestModel;
				requestModel = (HttpRequestHashModel) hash.get(FreemarkerManager.KEY_REQUEST);
				HttpServletRequest request = requestModel.getRequest();
				ServletContext context = request.getSession(true).getServletContext();
				// 使用web取得资源
				URL url = context.getResource(templatePath);
				if (url == null) {
					// 使用线程Loader取得资源
					url = ClassLoaderUtils.getResource(templatePath, this.getClass());
				}
				if (url != null) {
					StringBuffer sb = StringUtils.textReader(url.toURI());
					source += sb.toString();
				}
			}
		}
		return source;
	}
	@Override
	public void afterInvoke(Writer writer) {
		
	}
}
